package com.example.ch3_2tablayoutviewpager2test;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.TabHost;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private TabLayout tbl;
    private ViewPager2 vp2;
    //声明子页面集合数据源
    private List<Fragment> fragments;

    //声明子页面适配器
    private PageAdapter pageAdapter;



    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获取空间对象
        tbl = findViewById(R.id.tbl);
        vp2 = findViewById(R.id.vp2);

        //初始化子页面集合数据资源
        initPages();
        //初始化子页面适配器对象
        pageAdapter = new PageAdapter(fragments,this);
        //用来设置选项卡视图切换时的滑动方向
        vp2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
        //给viewPage2绑定适配器
        vp2.setAdapter(pageAdapter);
        //关联ViewPage2和TabLayout
        TabLayoutMediator mediator = new TabLayoutMediator(
                tbl,
                vp2,
                new TabLayoutMediator.TabConfigurationStrategy() {
                    @Override
                    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                        //设置选型卡的文本
                        switch (position){
                            case 0:
                                tab.setText("首页");
                                break;
                            case 1:
                                tab.setText("推荐");
                                break;
                            case 2:
                                tab.setText("我的");
                                break;
                            case 3:
                                tab.setText("设置");
                                break;
                        }
                    }
                }
        );
        //使viewPager2 和 tablayout 关联生效
        mediator.attach();



    }

    private void initPages() {
        //初始化集合对象
        fragments = new ArrayList<>();
        //添加Fragment元素对象
        fragments.add(new HomeFragment());
        fragments.add(new RecommendFragment());
        fragments.add(new MineFragment());
    }


}